import { useEffect, useState } from 'react';
import { Button, Space, Form, Row, Col, Table, Select, Popconfirm, Input } from 'antd';
import { PAGINATION_CONFIG } from '@/constants';
import { queryPriceTemplateList, savePriceTemplate,statusPriceTemplate } from '@/services/priceTemplate'
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import dayjs from 'dayjs';
import TableContainer from '@/components/TableContainer';
import { Access } from '@umijs/max';
import TableActions from '@/components/TableActions';
import FeeModal2 from './components/FeeModal2'

const statusTextMap = ['', '启用', '禁用', '已删除']

const PriceTemplatePage: React.FC = () => {
  const [searchForm] = Form.useForm<any>()
  const [searchParams, setSearchParams] = useState<any>({
    pageNum: 1, pageSize: 10,
  })
  const priceTemplateList = useRequest(() => queryPriceTemplateList(searchParams), {
    refreshDeps: [searchParams],
  })
  const save = useRequest(savePriceTemplate, {manual: true})
  const delA = useRequest(statusPriceTemplate, {manual: true})
  const [feeModalProps2, setFeeModalProps2] = useState<any>()

  const openEditModal = (record?: any, type?: string) => {
    setFeeModalProps2({
      open: true,
      station: record,
      type,
    })
  }
  const closeFeeModal2 = (reload?: boolean) => {
    if (reload) {
      priceTemplateList.refresh()
    }
    setFeeModalProps2({open: false})
  }
  const onFinish = (formValues: any) => {
    setSearchParams({
      ...searchParams,
      title: formValues.title,
      status: formValues.status,
      pageNum: 1,
    })
  }
  const del = (record: any) => {
    return delA.runAsync({infoId:record.id, status: 3}).then(priceTemplateList.refresh)
  }
  const disable = (record: any) => {
    return delA.runAsync({infoId:record.id, status: 2}).then(priceTemplateList.refresh)
  }
  const enable = (record: any) => {
    return delA.runAsync({infoId:record.id, status: 1}).then(priceTemplateList.refresh)
  }

  const columns: ColumnsType = [
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: status => statusTextMap[status] || '--',
    },
    {
      title: '添加时间',
      dataIndex: 'createTime',
      render: createTime => createTime ? dayjs(createTime).format('YYYY-MM-DD') : '--',
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 'max-content',
      fixed: 'right',
      render: (id: number, record) => {
        return <TableActions>
          <Access accessible={record.status === 2}>
            <a onClick={() => openEditModal(record, 'edit')}>编辑</a>
          </Access>
          <a onClick={() => openEditModal(record, 'detail')}>详情</a>
          <Access accessible={record.status === 1}>
            <Popconfirm
              title={`确定禁用吗?`}
              onConfirm={() => disable(record)}
            >
              <a>禁用</a>
            </Popconfirm>
          </Access>
          <Access accessible={record.status === 2}>
            <Popconfirm
              title={`确定启用吗?`}
              onConfirm={() => enable(record)}
            >
              <a>启用</a>
            </Popconfirm>
          </Access>
          <Access accessible={record.status === 2}>
            <Popconfirm
              title={`确定删除吗?`}
              onConfirm={() => del(record)}
            >
              <a>删除</a>
            </Popconfirm>
          </Access>
        </TableActions>
      }
    }
  ]

  useEffect(() => {
    const refresh = () => {
      priceTemplateList.refresh()
    }
    window.addEventListener('refreshPriceTemplateList', refresh)
    return () => {
      window.removeEventListener('refreshPriceTemplateList', refresh)
    }
  }, [])
  
  return (
    <TableContainer>
      <TableContainer.Toolbar>
        <Button type='primary' onClick={() => openEditModal()}>新建电价模板</Button>
      </TableContainer.Toolbar>
      <TableContainer.SearchContainer>
        <Form name='searchPriceTemplateForm' colon={false} form={searchForm} onFinish={onFinish}>
          <Row gutter={[20, 20]}>
            <Col span={6}>
              <Form.Item label='标题' name='title'>
                <Input placeholder='请输入' variant='borderless' allowClear />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label='状态' name='status'>
                <Select placeholder='请选择' options={[{label: '启用', value: 1}, {label: '禁用', value: 2}]} variant='borderless' style={{width: '100%'}} />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Space>
                <Button type='primary' htmlType='submit' loading={priceTemplateList.loading}>筛选</Button>
                <Button htmlType='reset'>重置</Button>
              </Space>
            </Col>
          </Row>
        </Form>
      </TableContainer.SearchContainer>
      <Table
        rowKey='id'
        loading={priceTemplateList.loading}
        dataSource={priceTemplateList.data?.data}
        columns={columns}
        scroll={{y: 700, x: 'max-content'}}
        pagination={{
          ...PAGINATION_CONFIG,
          current: searchParams.pageNum,
          pageSize: searchParams.pageSize,
          total: priceTemplateList.data?.totalCount || 0,
          onChange: (page, pageSize) => {
            setSearchParams({
              ...searchParams,
              pageNum: page === searchParams.pageNum ? 1 : page,
              pageSize,
            })
          }
        }}
      />
      <FeeModal2
        {...feeModalProps2}
        onCancel={closeFeeModal2}
      />
    </TableContainer>
  );
};

export default PriceTemplatePage;
